/**
 ***********************************************************************
 * Program name: DBCon.java<br>
 * Program description: TODO<br>
 * Author: sugen<br>
 * Revision history:1.0<br>
 * <br>
 * Description of Change	Programmer		Date<br>
 * ---------------------    ----------      ----<br>
 * Initial creation			Su Gen		   2011-3-10 <br>
 * <br>
 * Copyright (c) 2011 by SUGEN ALL RIGHTS RESERVED<br>
 ************************************************************************
 */
package com.common;

import java.sql.*;

public class DBCon {
	
	private Connection con;
	private ResultSet rs;

	public static Connection getConnection() throws SQLException {
		try {
			// 连接MS SQL Server数据库
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException ex) {
			ex.printStackTrace();
			return null;
		}
		// 设置连接的数据库名，登陆的用户名和密码
		return DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8","root", "admin");
	}

	// 执行SQL语句的查询操作
	public ResultSet executeQuery(String sql) {
		try {
			con = DBCon.getConnection();
			Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
			rs = statement.executeQuery(sql);
		} catch (SQLException ex) {
			ex.printStackTrace();
		}
		return rs;
	}

	// 执行SQL语句的更新操作
	public int executeUpdate(String sql) {
		int count = 0;
		Statement stmt = null;
		try {
			con = DBCon.getConnection();
			stmt = con.createStatement();
			count = stmt.executeUpdate(sql);
		} catch (SQLException ex) {
		} finally {
			try {
				if (stmt != null)
					stmt.close();
				if (con != null)
					con.close();
			} catch (SQLException ex) {
				System.err.print(ex);
			}
		}
		return count;
	}

	// 释放数据集rs，关闭数据库连接
	public void freeRs(ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
				con.close();
			}
		} catch (Exception e) {
		}
	}
}